package com.assessment.servermanager.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.ObjectUtil;
import com.assessment.servermanager.commen.entity.PageQuery;
import com.assessment.servermanager.commen.exception.ServiceException;
import com.assessment.servermanager.commen.page.TableDataInfo;
import com.assessment.servermanager.commen.utils.BeanCopyUtils;
import com.assessment.servermanager.commen.utils.StringUtils;
import com.assessment.servermanager.entity.TbAdvice;
import com.assessment.servermanager.entity.TbPaper;
import com.assessment.servermanager.entity.TbQuestion;
import com.assessment.servermanager.entity.bo.TbPaperBo;
import com.assessment.servermanager.entity.vo.TbEmployeeVo;
import com.assessment.servermanager.entity.vo.TbPaperVo;
import com.assessment.servermanager.mapper.TbPaperMapper;
import com.assessment.servermanager.service.ITbPaperService;
import com.assessment.servermanager.service.ITbQuestionService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author jiajia
 * @date 2023-08-28
 */
@Service
public class TbPaperServiceImpl implements ITbPaperService {
    @Autowired
    private TbPaperMapper tbPaperMapper;

    @Autowired
    private ITbQuestionService questionService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public TbPaper selectTbPaperById(Long id) {
        return tbPaperMapper.selectById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param tbPaperBo 【请填写功能名称】
     * @param pageQuery
     * @return 【请填写功能名称】
     */
    @Override
    public TableDataInfo<TbPaperVo> selectTbPaperList(TbPaperBo tbPaperBo, PageQuery pageQuery) {
        QueryWrapper<TbPaper> queryWrapper = new QueryWrapper<TbPaper>();
        queryWrapper.eq(StringUtils.isNotEmpty(tbPaperBo.getName()),"p.name",tbPaperBo.getName());
        queryWrapper.eq(tbPaperBo.getTotalScore() != null,"p.total_score",tbPaperBo.getTotalScore());
        queryWrapper.eq(tbPaperBo.getQuestionNum() != null,"p.question_num",tbPaperBo.getQuestionNum());
        queryWrapper.between(ObjectUtil.isNotNull(tbPaperBo.getExamTime()),"p.exam_time",tbPaperBo.getExamTimeStar(),tbPaperBo.getExamTimeEnd());
        queryWrapper.eq(tbPaperBo.getMinutes() !=null,"p.minutes",tbPaperBo.getMinutes());
        queryWrapper.eq(tbPaperBo.getStatus() !=null,"p.status",tbPaperBo.getStatus());
        queryWrapper.eq(tbPaperBo.getAid() != null,"p.aid",tbPaperBo.getAid());
        queryWrapper.between(ObjectUtil.isNotNull(tbPaperBo.getCreatedtime()),"p.createdtime",tbPaperBo.getCreatedTimeStart(),tbPaperBo.getCreatedTimeEnd());
        queryWrapper.eq("p.delFlag",0);
        Page<TbPaperVo> page =  tbPaperMapper.selectListPge(pageQuery.build(),queryWrapper);
        return TableDataInfo.build(page);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param tbPaper 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertTbPaper(TbPaperBo tbPaper) {
        TbPaper copy = BeanCopyUtils.copy(tbPaper,TbPaper.class);
        copy.setCreatedtime(new Date());
        return tbPaperMapper.insert(copy);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param tbPaper 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateTbPaper(TbPaper tbPaper) {
        return tbPaperMapper.updateById(tbPaper);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTbPaperByIds(Long[] ids) {
        return tbPaperMapper.deleteBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteTbPaperById(Long id) {
        return tbPaperMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int generterQuestionOrPublish(Long id, Integer type) {
        //根据id获取当前试卷信息
        TbPaper paper = tbPaperMapper.selectById(id);

        if(1==type){
            //判断 type为1时，不再继续生成试卷
            if(paper.getStatus()==1){
                throw new ServiceException("非法请求，试卷状态异常");
            }
            //生成试题
            //获取题目数量 并根据数量生成
            List<TbQuestion> questions = questionService.generterQuestion(paper.getQuestionNum());
            //将获取的题目的id收集起来，插入关联表
            List<Long> questionIds = questions.stream().map(TbQuestion::getId).collect(Collectors.toList());
            tbPaperMapper.insertPaperQuestion(questionIds,paper.getId());
            //修改试卷状态为已生成试题，待发布
            paper.setStatus(1);
            return tbPaperMapper.updateById(paper);
        }else{
            //发布试卷
            //查询试卷状态
            if(paper.getStatus()!=1){
                throw new ServiceException("非法请求，试卷状态异常");
            }
            //发布
            paper.setStatus(2);
            return tbPaperMapper.updateById(paper);
        }
    }

    @Override
    public List<TbQuestion> getQuestion(Long paperId) {
        //根据试卷id获取试题id列表
        return  questionService.selectQuestionByPaperId(paperId);
    }
}
